package com.example.sql.manager.controller;

import com.alibaba.fastjson.JSON;
import com.example.sql.manager.common.ResponseEntity;
import com.example.sql.manager.constants.Url;
import com.example.sql.manager.service.InvokeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;

@Api(value = "InvokeController", tags = {"Func 的调用接口"})
@Controller
@RequestMapping(Url.INVOKE)
public class InvokeController {

    private final Logger log = LoggerFactory.getLogger(InvokeController.class);

    @Resource
    private InvokeService invokeService;

    @ApiOperation(value = "根据 Id 调用 Func")
    @ResponseBody
    @PostMapping(value = "/func/{id:\\d+}")
    public Object func(
            @PathVariable Long id, @RequestBody Map<String, Object> params) throws Exception {
        log.info("\r\nid {}\r\n params {}", id, JSON.toJSONString(params));
        return invokeService.func(id, params);
    }

    @ApiOperation(value = "根据 Id 调用查询 Func")
    @ResponseBody
    @PostMapping(value = "/query/{id:\\d+}")
    public ResponseEntity<String, Object> query(
            @PathVariable Long id, @RequestBody Map<String, Object> params) {
        log.info("\r\nid {}\r\n params {}", id, JSON.toJSONString(params));
        try {
            Object res = invokeService.query(id, params);
            return ResponseEntity.success(res);
        } catch (Exception e) {
            return ResponseEntity.failure(e.getMessage());
        }
    }

    @ApiOperation(value = "根据 Id 调用更新 Func")
    @ResponseBody
    @PostMapping(value = "/update/{id:\\d+}")
    public ResponseEntity<String, Object> update(
            @PathVariable Long id, @RequestBody Map<String, Object> params) {
        log.info("\r\nid {}\r\n params {}", id, JSON.toJSONString(params));
        try {
            Object res = invokeService.update(id, params);
            return ResponseEntity.success(res);
        } catch (Exception e) {
            return ResponseEntity.failure(e.getMessage());
        }
    }
}
